package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.ILJAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author sdq
 * @Date 2022/8/29 15:38
 */
@Service
@Slf4j
public class LJAPIImpl implements ILJAPI {
    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;

    private static String LJURL = null;
    //拼装参数
    private Map<String,Object> params(AccountInfo accountInfo, SalePartner sa){
        LJURL = sa.getOther();
        Map<String,Object> params = new HashMap<>();
        params.put("proxyId",sa.getTwoOther());
        params.put("timestamp",(int)(System.currentTimeMillis()/1000));
        params.put("title","【"+descTitle + "_" + accountInfo.getId() + "】  "+ accountInfo.getLevel() + "  " + accountInfo.getDes());
        params.put("number",accountInfo.getId().toString());

        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(),sa);

        params.put("price",bigDecimal);
        params.put("intro",accountInfo.getDes());
        params.put("keyword","");
        params.put("photo",accountInfo.getTitleImg());
        //other  空格拼接主要参数
        params.put("other",accountInfo.getRegional() + " "+accountInfo.getLevel()+
                " 英雄数"+ accountInfo.getHeroes()+" 皮肤数"+accountInfo.getSkins()+
                " " + bigDecimal + " 营地号"+accountInfo.getCampId());
        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        if(!CollectionUtils.isEmpty(infoImgs)){
            params.put("content",infoImgs.stream().map(InfoImg::getImgUrl).collect(Collectors.joining(",")));
        }
        String str = sa.getTwoOther() + sa.getSaleKey() + params.get("timestamp");
        String sign = DigestUtils.md5Hex(str).toUpperCase();
        params.put("sign",sign);
        //1王者荣耀; 2原神; 3和平精英;4吃鸡
        if("王者荣耀".equals(accountInfo.getType())){
            params.put("gameId",1);
        }
        if("原神".equals(accountInfo.getType())){
            params.put("gameId",2);
        }
        if("和平精英".equals(accountInfo.getType())){
            params.put("gameId",3);
        }
        if("吃鸡".equals(accountInfo.getType())){
            params.put("gameId",4);
        }
        return params;
    }


    @Override
    public AjaxResult addGame(AccountInfo accountInfo,Long userId,SalePartner salePartner) {
        try{
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> params = params(accountInfo,salePartner);
            params.put("action","add");
            String paramsStr = JSONObject.toJSONString(params);
            log.info("龙将新增请求参数={}",paramsStr);
            String response = "";
            if (Objects.isNull(LJURL)){
                response = HttpUtils.sendPost(OutUrlConstant.LCURL, paramsStr, "application/json");
            }else {
                response = HttpUtils.sendPost(LJURL, paramsStr, "application/json");
            }

            log.info("龙将新增返回参数={}",response);
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!"200".equals(resultJson.getString("returnCode"))){
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",response);
            result.put("msg",msg);
            return AjaxResult.success(result);
        }catch (Exception e){
            throw new GlobalException(e.getMessage());
        }

    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        try{
            Map<String, Object> params = params(accountInfo,salePartner);
            params.put("action","edit");
            String paramsStr = JSONObject.toJSONString(params);
            log.info("龙将编辑请求参数={}",paramsStr);
            String response = "";
            if (Objects.isNull(LJURL)){
                response = HttpUtils.sendPost(OutUrlConstant.LCURL, paramsStr, "application/json");
            }else {
                response = HttpUtils.sendPost(LJURL, paramsStr, "application/json");
            }
            log.info("龙将编辑返回参数={}",response);
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            Map<String, Object> result = new HashMap<>();
            if (!"200".equals(resultJson.getString("returnCode"))){
                result.put("code",500);
            }else {
                result.put("code",200);
            }
            result.put("req",JSONObject.toJSONString(params));
            result.put("res",response);
            result.put("msg",msg);
            return AjaxResult.success(result);
        }catch (Exception e){
            throw new GlobalException(e.getMessage());
        }
    }

    @Override
    public AjaxResult delGame(AccountInfo accountInfo,Long userId,SalePartner sa) {
        Map<String, Object> params = params(accountInfo,sa);
        params.put("action","off");
        String paramsStr = JSONObject.toJSONString(params);
        log.info("龙将删除请求参数={}",paramsStr);
        String response = HttpUtils.sendPost(OutUrlConstant.LCURL, paramsStr, "application/json");
        log.info("龙将删除返回参数={}",response);
        JSONObject resultJson = JSONObject.parseObject(response);
        String msg = resultJson.getString("msg");
        msg = MapUntils.unicodeToString(msg);
        Map<String, Object> result = new HashMap<>();
        if (!"200".equals(resultJson.getString("returnCode"))){
            result.put("code",500);
        }else {
            result.put("code",200);
        }
        result.put("req",JSONObject.toJSONString(params));
        result.put("res",response);
        result.put("msg",msg);
        return AjaxResult.success(result);
    }

    public static void main(String[] args) {
        String proxyId = "lingcheng";
        String apiKey = "574C37BC368C7893472545574F9026ED";
        long timestamp = System.currentTimeMillis()/1000;
        System.out.println(timestamp);
        Map<String,Object> params = new HashMap<>();
        //add edit off
//        params.put("action","add");
//        params.put("action","edit");
        params.put("action","off");
        params.put("proxyId",proxyId);
        params.put("timestamp",(int)timestamp);
        params.put("gameId",1);//游戏平台编号 1王者荣耀; 2原神; 3和平精英;4吃鸡
        params.put("title","testadd");
        params.put("number","id");
        params.put("price",198);
        params.put("intro","描述");
        params.put("keyword","关键字");
        params.put("photo","商品首图 photoHttpUrl");
        params.put("content","商品图集 英文逗号分隔");

        String str = proxyId + apiKey + timestamp;
        System.out.println("str : "+str);
        String sign = DigestUtils.md5Hex(str).toUpperCase();
        params.put("sign",sign);
        System.out.println(sign);
        System.out.println(JSONObject.toJSONString(params));
        String baseUrl = "http://devxuanapi.ontheway168.cn/api/accept";
        String response = HttpUtils.sendPost(baseUrl, JSONObject.toJSONString(params), "application/json");
        System.out.println(response);
        long time = DateUtils.getNowDate().getTime();
        System.out.println(time);

    }
}
